//
//  BundleDownloadHandler.m
//  ocdemo
//
//  Created by mac on 2025/2/9.
//

#import "BundleDownloadHandler.h"
#import "ScriptLoadUtil.h"
#import <SSZipArchive.h>

@implementation BundleDownloadHandler

- (void)downloadBundle:(NSString *)urlStr moduleName:(NSString *)moduleName downloadCompleteHandle:(DownloadCompleteHandle)downloadCompleteHandler{
    if([ScriptLoadUtil isScriptLoaded:moduleName]){
        downloadCompleteHandler(YES,@"");
        return;
    }
    NSURL* url=[NSURL URLWithString:urlStr];
    NSURLSession* session=[NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask=[session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error!=nil){
            NSLog(@"下载失败 %@",error.localizedFailureReason);
            downloadCompleteHandler(NO,@"");
            return;
        }
        NSLog(@"下载成功");
        NSLog(@"下载成功 %@",response);
        //Document - BundleDownloaded
        //         - Bundles
        //1.拼接路径
        NSString * subDir=[@"BundleDownloaded" stringByAppendingPathComponent:response.suggestedFilename];
        NSString * desPath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:subDir];
        NSString * desPathDir=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"BundleDownloaded"];
        
        
        NSString * subScriptDir=[@"Bundles" stringByAppendingPathComponent:moduleName];
        NSString * bundlePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:subScriptDir];
        
        //2.生成对应目录 目录已存在 不会报错
        
        NSFileManager*mgr=[NSFileManager defaultManager];
        [mgr createDirectoryAtPath:desPathDir withIntermediateDirectories:YES attributes:nil  error:nil];
        [mgr createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil  error:nil];
        
        //3.将下载的文件放到对应的目录
        NSError*moveError=nil;
        [mgr removeItemAtURL:[NSURL fileURLWithPath:desPath] error:nil];
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:desPath] error:&moveError];
        if(moveError!=nil){
            NSLog(@"转存失败 %li",(long)moveError.code);
            if(moveError.code!=516){//文件名相同 覆盖不了
                downloadCompleteHandler(NO,@"");
            }
        }
        //4.解压
        @try {
            [SSZipArchive  unzipFileAtPath:desPath toDestination:bundlePath];
//            NSError*moveError=nil;
//            [mgr removeItemAtURL:[NSURL URLWithString:subScriptDir] error:nil];
//            [mgr moveItemAtURL:location toURL:[NSURL URLWithString:bundlePath]  error:&moveError];
            downloadCompleteHandler(YES,bundlePath);
        } @catch (NSException *exception) {
            NSLog(@"解压失败 %@",exception);
            downloadCompleteHandler(NO,@"");
        } @finally {
            
        }
        
    }];
    // 必须调用 resume 启动任务
    [downloadTask resume];
    
}
@end
